package cn.wolfcode.wolf2w.redis.service.impl;

import cn.wolfcode.wolf2w.redis.service.IVisitorRedisService;
import cn.wolfcode.wolf2w.util.DateUtil;
import cn.wolfcode.wolf2w.util.RedisKeysStandard;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class VisitorRedisServiceImpl implements IVisitorRedisService {
    @Autowired
    private StringRedisTemplate template;
    @Override
    public int getTodayView(String ownerId) {
        String key = RedisKeysStandard.TODAY_VIEW.addKeyMessage(ownerId);
        // 获取当前时间到今天最后一秒时间
        Date endDate = DateUtil.getEndDate(new Date());
        long time = DateUtil.getDateBetween(endDate, new Date());
        template.opsForValue().setIfAbsent(key, "0", time, TimeUnit.SECONDS);
        String todayView = template.opsForValue().get(key);
        return Integer.valueOf(todayView);
    }

    @Override
    public void incrementValue(String keyMsg) {
        String key = RedisKeysStandard.TODAY_VIEW.addKeyMessage(keyMsg);
        // 获取当前时间到今天最后一秒时间
        Date endDate = DateUtil.getEndDate(new Date());
        long time = DateUtil.getDateBetween(endDate, new Date());
        template.opsForValue().setIfAbsent(key, "0", time, TimeUnit.SECONDS);
        template.opsForValue().increment(key);
    }
}
